<template>
  <div>
    <div
        style="width: 1670px;min-height:770px;padding:24px 32px;margin:15px 0 15px 35px;
        border-radius: 26px;background-color: white">
      <div v-if="taskShow" style="width: 800px">
        <p style="margin: 0;font-size: 18px">测验与作业</p>
        <el-collapse v-model="activeNames" @change="handleChange" style="margin-top: 20px">
          <el-collapse-item v-for="(item,index) in chapterList" :title="item.chapterName" :name="index">
            <div v-for="(it,ind) in taskList" v-if="it.chapterId===item.chapterId"
                 style="margin: 20px 0 30px 30px" :id="'task'+index+'-'+ind">
              <el-link :href="'/#/learn/testList/'+item.courseId+'/'+item.chapterId+'/'+it.taskId"
                       style="font-size: 16px;" :underline="false">
                <div style="display: flex">
                  <a v-if="it.subMitFlag" class="el-icon-circle-check" style="border-radius: 50%;
                background-color: #409EFF;color: white;font-size: 24px;height: 24px;width: 24px"></a>
                  <a v-else class="el-icon-remove-outline" style="font-size: 24px;"></a>
                  <div style="margin: 4px 0 0 8px">{{ it.taskName }}</div>
                </div>
              </el-link>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div v-if="!taskShow">
        <p style="margin: 0;font-size: 18px">
          <el-form style="display: flex">
            <a style="margin-top: 6px">测验与作业</a>
            <i class="el-icon-arrow-right" style="margin: 10px"></i>
            <el-form-item style="width: 150px">
              <el-select v-model="chapterId" placeholder="请选择章节">
                <el-option @click.native="onClickChapter" v-for="(item,index) in chapterList"
                           :key="item.chapterId" :label="item.chapterName" :value="item.chapterId"></el-option>
              </el-select>
            </el-form-item>
            <i class="el-icon-arrow-right" style="margin: 10px"></i>
            <el-form-item style="width: 150px">
              <el-select v-model="taskId" placeholder="请选择作业">
                <el-option @click.native="onClickTask()" v-for="(item,index) in taskList"
                           v-if="item.chapterId===chapterId"
                           :key="item.taskId" :label="item.taskName" :value="item.taskId"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </p>
        <el-form :model="taskscore" :rules="rules" label-width="30px" style="display: flex;flex-direction: column;width: 800px" ref="taskscoreForm">
          <h4 style="margin:0 0 0 30px;">作业题目</h4>
          <div v-html="this.task.content" style="margin:0 0 30px 40px;">
        </div>
          <h4 style="margin:0 0 10px 30px;">作答</h4>
            <el-form-item prop="content">
              <div id="div1">
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addOrUpdate('taskscoreForm')">提 交</el-button>
            </el-form-item>
            <h4 style="margin:0 0 10px 30px;">提交次数: <a v-if="taskscore.submitNum">{{taskscore.submitNum}}</a>
              <a v-else>0</a> / {{task.submitnum}}</h4>
            <h4 style="margin:0 0 10px 30px;">作业得分：<a v-if="taskscore.score">{{taskscore.score}}</a>
              <a v-else>未批改</a> / {{task.score}}</h4>
          <div v-if="taskscore.scoreContent&&taskscore.scoreContent!==''">
          <h4 style="margin:0 0 0 30px;">评语</h4>
          <div v-html="taskscore.scoreContent" style="margin:0 0 30px 40px;">
          </div>
          </div>
          </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import E from 'wangeditor'
export default {
  name: "TestListView",
  data() {
    return {
      activeNames: ['1'],
      courseId: '',
      chapterId: '',
      taskId: '',
      task: '',
      isChange:false,
      taskscore:{content:''},
      taskscoreFlag:false,
      chapterList: [],
      taskList: [],
      taskShow: false,
      rules: {
        content:{required: true, message: '作答不能为空', trigger: 'blur'}
      }
    }
  },
  watch:{
    taskscore(val){
      if(!this.isChange){
        this.editor.txt.html(this.taskscore.content);
      }
      this.isChange=false;
    }
  },
  methods: {
    getChapterByCourseId(courseId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/chapter/selectChapterByCourseId/${courseId}`
      }).then(res => {
        this.chapterList = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    getTaskByCourseId(courseId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/user/task/selectTaskByCourseId/${courseId}`
      }).then(res => {
        if(res.data.code===200)
          this.taskList = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    getTaskByTaskId(taskId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/task/selectTaskById/${taskId}`
      }).then(res => {
        if (res.data.code === 200)
          this.task = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    getTaskScoreByUserAndTask(){
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/taskscore/selectTaskscoreByUserAndTask/${localStorage.getItem('userId')}/${this.taskId}`,
      }).then(res => {
        if (res.data.code === 200){
          this.taskscore=res.data.dataobject;
          this.taskscoreFlag=true;
        }
        else
          this.taskscoreFlag=false;
      }).catch(err => console.log(err));
    },
    addTaskScore(){
      this.$axios({
        method: 'post',
        url: "http://localhost:8089/taskscore/createTaskscore",
        data:this.taskscore
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success("提交作业成功")
          this.getTaskScoreByUserAndTask()
        }
        else
          this.$message.error("提交作业失败")
      }).catch(err => console.log(err));
    },
    updateTaskScore(){
      this.$axios({
        method: 'post',
        url: "http://localhost:8089/taskscore/updateTaskscore",
        data:this.taskscore
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success("修改作业成功")
          this.getTaskScoreByUserAndTask()
        }
        else
          this.$message.error("您的提交次数已达上限，提交作业失败")
      }).catch(err => console.log(err));
    },
    //创建富文本编辑器，并进行上传图片、上传视颜的配置
    createRichTextEditor() {
      this.editor = new E('#div1');
      this.editor.config.uploadImgServer = 'http://localhost:8089/richText/uploadFile?type=img';
      this.editor.config.uploadFileName = 'file';
      this.editor.config.uploadVideoServer = 'http://localhost:8089/richText/uploadFile?type=video';
      this.editor.config.uploadVideoName = 'file';
      this.editor.config.placeholder = '请在此处作答';
      this.editor.config.zIndex=500
      this.editor.config.onchange = (html)=>{
        this.isChange = true;
        this.taskscore.content=html//绑定当前逐渐地值
      }
      this.editor.create();
    },
    //确定按钮
    addOrUpdate(formName) {
      console.log(this.editor.txt.html());
      this.taskscore.content=this.editor.txt.html();
      this.taskscore.userId=localStorage.getItem('userId');
      this.taskscore.taskId=this.taskId;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.taskscoreFlag){
            if(this.taskscore.submitNum<this.task.submitnum){
              this.taskscore.submitNum=this.taskscore.submitNum+1;
              this.updateTaskScore();
            }else
              this.$message.error('提交次数已达上限')
          }
          else {
            this.taskscore.submitNum=this.taskscore.submitNum+1;
            this.addTaskScore();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleChange(val) {
      console.log(val);
    },
    onClickChapter() {
      this.taskId = '';
    },
    onClickTask() {
      this.$router.push({
        path: '/learn/testList/' + this.courseId + '/' + this.chapterId + '/' + this.taskId
      }).catch(err => console.log(err));
    }
  },
  created() {
    this.courseId = parseInt(this.$route.params.courseId);
    this.chapterId = parseInt(this.$route.params.chapterId);
    this.taskId = parseInt(this.$route.params.taskId);
    this.getChapterByCourseId(this.courseId);
    this.getTaskByCourseId(this.courseId);
    this.taskscore={content:''}
    if (!this.taskId) {
      this.taskShow = true;
    }
    else{
      this.getTaskByTaskId(this.taskId)
      this.getTaskScoreByUserAndTask()
      this.$nextTick(() => {
        if (!this.editor) {
          this.createRichTextEditor();
        }
      });
    }
  },
}
</script>

<style scoped>
/deep/ .el-collapse-item__header {
  color: #333333;
  font-size: 16px;
  margin-top: 15px;
  border-radius: 10px;
  padding: 5px 20px;
  background-color: #F7F7F7 !important;
  position: relative;
}

/deep/ .el-collapse-item__content {
  text-align: left;
//color: #fff ; //background-color: #313743; padding-bottom: 0;

  div {
    height: .96rem;
    line-height: .96rem;
  }
}
</style>